<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-form :inline="true">
        <el-form-item label=" 机构  "  prop="departmentId">
          <el-select v-model="listQuery.departmentId" clearable placeholder="请选择">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="商户名称">
          <el-input v-model="listQuery.merchantName" clearable class="filter-item" placeholder="商户名称"/>
        </el-form-item>
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
        <el-button
          v-hasPermi="['admin:merchant:create']"
          class="filter-item"
          style="float:right"
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd">添加</el-button>
      </el-form>
    </div>
    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row >
      <el-table-column align="center" label="机构名称" prop="departmentName" />
      <el-table-column align="center" label="商户名称" prop="merchantName" />
      <el-table-column align="center" label="停车场" prop="parkVos">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" placement="top">
            <div slot="content">{{ scope.row.parkVos|filterText }}</div>
            <div class="diy-truncate">{{ scope.row.parkVos|filterText }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column align="center" label="发放记录" prop="couponCount">
        <template slot-scope="{row}">
          <router-link v-hasPermi="['admin:merchant:couponList']" :to="`/coupons/sendRecords?merchantId=${row.id}`" class="link">
            {{ row.couponCount }}
          </router-link>
        </template>
      </el-table-column>
      <el-table-column align="center" label="商家余额" prop="balance"/>

      <el-table-column align="center" label="操作" width="240" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['admin:merchant:update']"
            type="primary"
            size="small"
            @click="handleEdit(scope.row)">编辑</el-button>
          <!-- <el-button
            v-hasPermi="['admin:merchant:delete']"
            type="primary"
            size="small"
            @click="handleDelete(scope.row)">删除</el-button> -->
          <el-button
            v-hasPermi="['admin:merchantBackendRecharge:create']"
            type="primary"
            size="small"
            @click="handleTopup(scope.row)">充值</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />
    <!-- 弹窗表单 -->
    <el-dialog :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      :title="dialogType===1?'新增商家':'编辑商家'"
      width="40%">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label=" 机构名称  " prop="departmentId">
          <el-select :disabled="dialogType === 2"
          v-model="form.departmentId" placeholder="请选择" style="width:100%;" @change="handleDeptChange">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label=" 组织  " prop="organizationId">
          <el-select v-model="form.organizationId" placeholder="请选择" @change="handlezuzhiChange">
            <el-option
              v-for="item in orangeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="商家名称" prop="merchantName">
          <el-input v-model="form.merchantName"/>
        </el-form-item>
        <el-form-item label="停车场" prop="parkIds">
          <el-select
          v-model="form.parkIds" multiple placeholder="请选择停车场">
            <el-option v-for="item in parkIdsList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券类型" prop="merchantCouponType">
          <el-select v-model="form.merchantCouponType" placeholder="请选择活动区域">
            <el-option :value="1" label="满减券"/>
            <el-option :value="2" label="全免券"/>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-row>
            <el-col :span="12">
              <el-input v-model="form.phoneNumber"/>
            </el-col>
            <el-col :span="12">
              <el-button type="primary" @click="handleCheckPhone">添加管理员</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <div class="admin-list">
          <el-tag
            v-for="tag in form.userIds"
            :key="tag.id"
            :disable-transitions="false"
            closable
            @close="handleCloseTag(tag)">
            {{ tag.phoneNumber }}
          </el-tag>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :close-on-click-modal="false"
      :visible.sync="dialogVisibleTopUp"
      title="商家充值"
      width="30%">
      <el-form ref="topupForm" :model="topUpform" :rules="rules" label-width="100px">
        <el-form-item label="充值金额" prop="money">
          <el-input v-model="topUpform.money" type="Number"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="topUpform.remark" type="textarea"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleTopUp = false">取 消</el-button>
        <el-button type="primary" @click="submitTopup('topupForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, merchantGetUser, addMerchant, editMerchant, delMerchant, getMerchantDetail, addRecharge,listAuthPark } from './api/index'
import { getDepartmentList } from '@/api/base'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { listOrgs } from '@/api/system/organization'
export default {
  components: { Pagination },
  filters: {
    filterText(val) {
      return val.map(item => {
        return item.parkName
      }).join(',')
    }
  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        pageSize: 20
      },
      // 新增商家
      dialogVisible: false,
      dialogType: '新增商家',
      form: { userIds: [], parkIds: [] },
      rules: {
        departmentId: [
          { required: true, message: '请选择机构', trigger: 'blur' }
        ],
        merchantName: [
          { required: true, message: '请输入商家名称', trigger: 'blur' }
        ],
        parkIds: [
          { required: true, message: '请选择开放片区', trigger: 'blur' }
        ],
        merchantCouponType: [
          { required: true, message: '请选择优惠券类型', trigger: 'blur' }
        ],
        money: [
          { required: true, message: '请输入充值金额', trigger: 'blur' }
        ],
        organizationId: [{ required: true, message: '请选择组织', validator: this.checkSelected, trigger: 'change' }],
      },
      // 商家充值
      topUpform: { merchantId: null },
      dialogVisibleTopUp: false,
      departmentList: [],
      parkIdsList: [],
      orangeList:[],//组织数据
    }
  },
  created() {
    this.getList()
    this.getDepartmentList()
  },
  methods: {
    getDepartmentList(){//获取机构
      getDepartmentList().then(res => {
        this.departmentList = res.data || []
      })
    },
    async listOrgs(departmentId){//根据机构获取组织
      let res = await listOrgs({departmentId})
    	let list = res.data || []
    	this.orangeList = [...list]
    },
    submitTopup(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          addRecharge(this.topUpform).then(res => {
            this.dialogVisibleTopUp = false
            this.getList()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleTopup(row) {
      console.log(row)
      this.dialogVisibleTopUp = true
      this.topUpform.merchantId = row.id
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogType === 1) {
            addMerchant(this.form).then(res => {
              this.dialogVisible = false
              this.getList()
            })
          } else {
            editMerchant(this.form).then(res => {
              this.dialogVisible = false
              this.getList()
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleCloseTag(tag) {
      this.form.userIds.splice(this.form.userIds.indexOf(tag), 1)
    },
    handleCheckPhone() {
      const re = /^1[3,4,5,6,7,8,9][0-9]{9}$/
      const result = re.test(this.form.phoneNumber)
      if (!result) {
        this.$message.error('请输入正确的手机号')
        return false
      }
      if(!this.form.departmentId) return this.$message.error('请选择机构')
      merchantGetUser({
        departmentId: this.form.departmentId,
        phoneNumber:this.form.phoneNumber,
      }).then(res => {
        const data = res.data
        this.form.userIds.push({
          userId: data.id,
          phoneNumber: data.phoneNumber
        })
        this.form.phoneNumber = null
      })
    },
    async handleDeptChange(val, flag = false) {
			this.parkIdsList = []
			this.orangeList= []
      let form = {...this.form}
      form.organizationId = ''
			form.parkIds = []
      form.userIds = []
      this.form = {...form}
      this.listOrgs(val)
    },
		async handlezuzhiChange(val){
			let form = {...this.form}
			form.parkIds = []
			this.form = {...form}
			this.getParkList(val)
		},
		async getParkList(val){
			let res = await listAuthPark({
				// departmentId:this.form.departmentId,
				organizationId:val,
			})
			let data = res.data || []
			this.parkIdsList = data
		},
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        let data = response.data || {}
        this.list = data.list || []
        this.total = Number(data.total || 0)
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    handleEdit(row) {
      this.reset()
      getMerchantDetail(row.id).then(res => {
        // console.log(res)
        const result = res.data || {}
        result.parkIds = result.parkVos.map(item => {
          return item.parkId
        })
        result.userIds = result.userVos || []
        this.form = { ...result }
        this.dialogVisible = true
        this.dialogType = 2
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
        this.listOrgs(this.form.departmentId)
				this.getParkList(this.form.organizationId)
      })
    },
    reset() {
      this.form = {
        departmentId: [],
        userIds: [],
        parkIds: [],
        merchantName: '',
        merchantCouponType: '',
        phoneNumber: ''
      }
      this.orangeList = []
    },
    handleDelete(row) {
      this.$confirm(`确定删除商户:${row.merchantName}?`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delMerchant(row.id).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleAdd() {
      this.dialogType = 1
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
      this.reset()
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>
<style scoped lang="scss">
.admin-list{
  border: 1px solid #BEBDBD;
  box-shadow: 0px 2px 3px 0px rgba(64,158,255,0.1608);
  border-radius: 1px 1px 1px 1px;
  padding: 5px;
  height: 80px;
}
.el-tag + .el-tag {
    margin-left: 10px;
  }
  .link{
    color: #4888F6;
    text-decoration: underline;
  }
</style>
